package gogsci

import (
	"bytes"
	"context"
	"fmt"
	"os/exec"
	"time"
)

func ExecuteScript(script string, env Environment, args ...string) string {
	cmd := exec.Command("bash", append([]string{"-c", script}, args...)...)
	buf := bytes.NewBuffer(nil)

	cmd.Stdout = buf
	cmd.Stderr = buf
	cmd.Env = env.ENV()

	var errCh = make(chan error, 1)
	timeOut := time.Hour * 1

	ctx, cancel := context.WithTimeout(context.Background(), timeOut)
	defer cancel()

	go func() {
		errCh <- cmd.Run()
	}()

	select {
	case er := <-errCh:
		if er != nil {
			buf.WriteString(fmt.Sprintf("script %s exec failed: %v", script, er))
		}
	case <-ctx.Done():
		cmd.Process.Kill()
		buf.WriteString(fmt.Sprintf("script %s exec timeout after %s, canceled", script, timeOut))
	}

	return buf.String()
}
